<template>
	<div class="conter">
		<view class="bg" v-if="!remoteUserId">
			<view class="box">
				<view class="boxConter">
					<view class="boxConterTime">
						<u-circle-progress active-color="#17b0b7" :percent="percentageTime(timer)">
							<view class="u-progress-content">
								<view class='u-progress-info'>{{formatTime(timer)}}</view>
							</view>
						</u-circle-progress>
					</view>
					<view class="boxConterTitle">抽查照片</view>
					<view class="boxConterFlex">
						<image class="boxConterImg" @click="switchCamera" mode="widthFix"
							v-for="(item,index) in inspectList" :key="index" :src="$wanlshop.oss(item.info)"></image>
						<!-- <image class="boxConterImg" mode="widthFix" :src="imgs"></image> -->
					</view>


					<!-- <view class="boxConterBtn" @click="snapshotVideo">截图</view> -->
					<view class="boxConterBtn" @click="exitRoom">结束服务</view>
				</view>
			</view>
		</view>
		<view class="plug" id='root' v-if="remoteUserId">
			<trtc-local-view :viewId="userId" class="trtcView"></trtc-local-view>
			<trtc-remote-view :userId="remoteUserId" :viewId="remoteUserId" v-if="remoteUserId"
				style="width: 200rpx;height: 300rpx;flex: 1;position: fixed;top: 100rpx;z-index: 99999999;right: 30rpx;">
			</trtc-remote-view>
		</view>
	</div>
</template>

<script>
	import permision from "@/common/permission.js"
	import TrtcCloud from '@/TrtcCloud/lib/index';
	import {
		TRTCAppScene,
		TRTCVideoStreamType,
		TRTCAudioRoute,
		TRTCAudioQuality,
		TRTCVideoResolution,
		TRTCVideoResolutionMode,
		TRTCVideoEncParam
	} from '@/TrtcCloud/lib/TrtcDefines';
	import genTestUserSig from '@/debug/GenerateTestUserSig';
	import TrtcLocalView from '@/TrtcCloud/view/TrtcLocalView';
	import TrtcRemoteView from '@/TrtcCloud/view/TrtcRemoteView';
	// const roomId = Math.floor(Math.random() * 100000).toString();
	export default {
		components: {
			TrtcLocalView: TrtcLocalView,
			TrtcRemoteView: TrtcRemoteView,
		},
		data() {
			return {
				trtcCloud: null,
				sdkAppId: 0,
				userSig: '',
				// roomId: Math.floor(Math.random() * 100000),
				roomId: '',
				userId: '',
				windowHeight: '',
				appScene: TRTCAppScene.TRTCAppSceneVideoCall, // TRTCAppSceneVideoCall
				isFrontCamera: true,
				streamType: TRTCVideoStreamType.TRTCVideoStreamTypeBig,
				remoteUserId: '',
				audioRoute: TRTCAudioRoute.TRTCAudioRouteSpeaker,
				remoteAudioMuteState: false,
				localAudioMuteState: false,
				localVideoMuteState: false,
				timer: 0,
				timeCilck: null,
				messageList: [],
				inspectList: getApp().globalData.inspectList || [],
				delay: 0,
				timeImg: null,
				type: null,
				num: 0
			}
		},
		watch: {
			inspectList(newVal, oldVal) {
				console.log("新", newVal)
				console.log("老", oldVal)
				if (this.num < 5) {
					this.countDown()
				}

			}
		},
		mounted() {

			this.timeCilck = setInterval(() => {
				this.timer++;
				if (this.type == 'insurance') {
					if (this.timer >= 7200) {
						clearInterval(this.timeCilck);
						this.exitRoom()
					}
				} else {
					if (this.timer >= 31536000) {
						clearInterval(this.timeCilck);
						this.exitRoom()
					}
				}

				// console.log(this.timer)
			}, 1000);

		},
		onLoad(e) {
			this.userId = e.userId
			this.roomId = e.roomId
			this.type = e.type
			// console.log("format",this.$moment().format('X'))// 返回值为字符串类型
			// console.log("unix",this.$moment().unix())
			const date = Number(this.$moment().unix()) - Number(e.timestamp)
			// console.log("date",date)
			this.timer = date
			if (uni.getDeviceInfo().platform === 'android') {
				permision.requestAndroidPermission('android.permission.RECORD_AUDIO');
				permision.requestAndroidPermission('android.permission.CAMERA');
			}
			// 保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			});
			// 生成 userSig
			const {
				sdkAppId,
				userSig
			} = genTestUserSig(this.userId);
			this.sdkAppId = sdkAppId;
			this.userSig = userSig;
			if (!sdkAppId || !userSig) {
				uni.showToast({
					title: '请填写 sdkAppId、userSig',
					icon: 'none'
				});
			}
		},
		onReady() {
			this.enterRoom()
		},
		onUnload() {
			this.destroyInstance();
			console.log('- onUnload');
		},
		unmounted() {
			this.handleUninstallEvents();
		},
		onBackPress() {
			this.destroyInstance();
		},
		methods: {

			countDown() {
				let delay = Math.round(Math.random() * 20) * 60 * 1000
				console.log("delay", delay)
				this.num = this.num++
				this.timeImg = setTimeout(() => {
					this.snapshotVideo()
				}, delay)
			},
			// 截屏
			snapshotVideo() {
				console.log("点击截图")
				this.trtcCloud.snapshotVideo(null, TRTCVideoStreamType.TRTCVideoStreamTypeBig);

			},


			saveImage(base64Data) {
				var that = this
				try {
					let bitmap = new plus.nativeObj.Bitmap();
					bitmap.loadBase64Data(base64Data, () => {
						const url = "_doc/" + new Date().getTime() + ".png"; // url为时间戳命名方式
						console.log('saveHeadImgFile', url);
						bitmap.save(url, {
							overwrite: true
						}, (i) => {
							console.log("url", url)
							let img = url
							uni.request({
								url: '/wanlshop/common/uploadData',
								success: updata => {
									console.log("上传图片", updata)
									// 读取图片宽高
									uni.getImageInfo({
										src: img,
										success: image => {
											uni.uploadFile({
												url: updata.data.uploadurl,
												filePath: image.path,
												name: 'file',
												formData: updata.data
													.storage == 'local' ?
													null : updata.data
													.multipart,
												success: data => {
													console.log(
														"cxzcxzcz",
														JSON.parse(
															data
															.data))
													const arr =
														getApp()
														.globalData
														.inspectList ||
														[]
													let str = {
														info: ''
													}
													str.info = JSON
														.parse(data
															.data).data
														.fullurl
													that.trtcUpload(
														JSON.parse(
															data
															.data)
														.data
														.fullurl)
													arr.push(str)
													getApp().globalData
														.inspectList =
														arr
												},
												fail: error => {
													console.log(error)
													this.$wanlshop.msg(
														JSON.parse(
															error
															.data)
														.msg);
												}
											});
										}
									});
								}
							})
							bitmap.clear()
						}, (e) => {
							// uni.showToast({
							// 	title: '图片保存失败',
							// 	icon: 'none'
							// })
							bitmap.clear()
						});
					});
				} catch (e) {
					//TODO handle the exception
				}

			},
			// 上传照片到trtc
			trtcUpload(img) {
				uni.request({
					url: '/trtc/uploadImage',
					data: {
						room_id: this.roomId,
						image: img
					},
					method: 'POST',
					success: res => {
						console.log("详情", res)

					}
				});
			},
			formatTime(time) {
				// 将时间格式化为 hh:mm:ss 的形式
				let hour = Math.floor(time / 3600);
				let minute = Math.floor((time - hour * 3600) / 60);
				let second = Math.floor(time - hour * 3600 - minute * 60);
				return `${hour.toString().padStart(2, '0')}:${minute
			        .toString()
			        .padStart(2, '0')}:${second.toString().padStart(2, '0')}`;
			},
			percentageTime(time) {
				if (this.type == 'insurance') {
					const second = 7200
					return (time / second) * 100
				} else {
					const second = 31536000
					return (time / second) * 100
				}

			},
			bindInputChange(event, type) {
				const value = event.detail.value;
				switch (type) {
					case 'roomId': {
						this.roomId = value;
						break;
					}
					case 'userId': {
						this.userId = value;
						break;
					}
				}
			},
			destroyInstance() {
				if (this.trtcCloud) {
					TrtcCloud.destroyInstance();
					this.trtcCloud = null;
					// uni.showToast({
					// 	title: '销毁实例',
					// 	icon: 'none'
					// });
				}
			},
			createTrtcCloud() {
				// uni.showToast({
				// 	title: '创建实例 ',
				// 	icon: 'none',
				// });
				this.trtcCloud = TrtcCloud.createInstance();
				this.handleEvents();
			},
			enterRoom() {
				try {
					// 【1】创建实例
					this.createTrtcCloud();
					// 【2】进房
					const {
						roomId,
						userId,
						sdkAppId,
						appScene,
						userSig
					} = this;
					console.log("this+++", this.roomId)
					let param = {
						strRoomId: roomId,
						userId,
						sdkAppId,
						userSig
					};
					console.log("param>>>>>", param)
					this.trtcCloud.enterRoom(param, appScene);
					// uni.showToast({
					// 	title: 'enterRoom ',
					// 	icon: 'none',
					// });
					this.startLocalPreview()
					this.countDown()
				} catch (error) {
					console.log(`enterRoom error = ${JSON.stringify(error)}`);
				}
			},
			exitRoom() {
				try {
					this.stopLocalPreview();
					this.stopRemoteView();
					this.stopLocalAudio();
					this.trtcCloud.exitRoom();
					this.remoteUserId = '';
					this.handleUninstallEvents();
					this.destroyInstance();
					setTimeout(() => {
						uni.navigateBack({
							delta: 2
						})
					}, 1000)
					clearInterval(this.timeCilck);
					clearTimeout(this.timeImg);
				} catch (e) {
					// TODO handle the exception
				}
			},
			// 本地预览
			startLocalPreview() {
				this.trtcCloud.startLocalPreview(this.isFrontCamera, this.userId);
				this.startLocalAudio()
				// uni.showToast({
				// 	title: 'localPreview',
				// 	icon: 'none',
				// });
			},
			// 停止本地预览
			stopLocalPreview() {
				this.trtcCloud.stopLocalPreview();
			},
			// 切前置、后置
			switchCamera() {
				this.isFrontCamera = !this.isFrontCamera;
				this.trtcCloud.switchCamera(this.isFrontCamera);
			},
			muteLocalVideo() {
				this.localVideoMuteState = !this.localVideoMuteState;
				this.trtcCloud.muteLocalVideo(TRTCVideoStreamType.TRTCVideoStreamTypeBig, this.localVideoMuteState);
			},
			startLocalAudio() {
				try {
					this.trtcCloud.startLocalAudio();
					// uni.showToast({
					// 	title: 'start local audio',
					// 	icon: 'none'
					// })
				} catch (e) {

				}
			},
			stopLocalAudio() {
				this.trtcCloud.stopLocalAudio();
			},
			muteLocalAudio() {
				this.localAudioMuteState = !this.localAudioMuteState;
				this.trtcCloud.muteLocalAudio(this.localAudioMuteState);
			},
			startRemoteView() {
				if (this.remoteUserId) {
					this.trtcCloud.startRemoteView(this.remoteUserId, this.streamType, this.remoteUserId);
					// uni.showToast({
					// 	title: `the remoteUserId: ${this.remoteUserId}`,
					// 	icon: 'none',
					// });
				} else {
					// uni.showToast({
					// 	title: '无远端用户',
					// 	icon: 'none',
					// });
				}
			},
			stopRemoteView() {
				if (this.remoteUserId) {
					this.trtcCloud.stopRemoteView(this.remoteUserId, this.streamType);
				}
			},
			muteRemoteAudio() {
				this.remoteAudioMuteState = !this.remoteAudioMuteState;
				console.log('远端用户 id = ', this.remoteUserId, '状态 = ', this.remoteAudioMuteState);
				this.remoteUserId && this.trtcCloud.muteRemoteAudio(this.remoteUserId, this.remoteAudioMuteState);
			},
			// 听筒、免提 切换
			switchAudioRoute() {
				this.audioRoute = this.audioRoute === TRTCAudioRoute.TRTCAudioRouteSpeaker ? TRTCAudioRoute
					.TRTCAudioRouteEarpiece : TRTCAudioRoute.TRTCAudioRouteSpeaker;
				this.trtcCloud.setAudioRoute(this.audioRoute);
			},
			handleEvents() {
				const videoResolution = TRTCVideoResolution.TRTCVideoResolution_480_360;
				const videoResolutionMode = TRTCVideoResolutionMode.TRTCVideoResolutionModePortrait; // 竖屏采集
				const videoFps = 15;
				const videoBitrate = 800;
				const minVideoBitrate = 200;
				const enableAdjustRes = false;
				console.warn('--- 分辨率 = ', videoResolution, videoResolutionMode, videoFps, videoBitrate);
				const param = new TRTCVideoEncParam(videoResolution, videoResolutionMode, videoFps, videoBitrate,
					enableAdjustRes);
				this.trtcCloud.setVideoEncoderParam(param);
				this.trtcCloud.on('onWarning', (res) => {
					// uni.showToast({
					// 	title: `onWarning: ${JSON.stringify(res)}`,
					// 	icon: 'none',
					// });
				});
				this.trtcCloud.on('onError', (res) => {
					console.log('- onError: ', JSON.stringify(res));
					// uni.showToast({
					// 	title: `error: ${JSON.stringify(res)}`,
					// 	icon: 'none',
					// });
				});
				this.trtcCloud.on('onEnterRoom', (result) => {
					console.log(`- onEnterRoom = ${result}`);
					if (result > 0) {
						this.trtcStart()
						uni.showToast({
							title: `进房成功，耗时: ${result}ms`,
							icon: 'none',
						});
					} else {
						console.log(`enter room failed，error code = ${result}`);
					}
				});
				this.trtcCloud.on('onExitRoom', (reason) => {
					const reasonList = ['主动调用 exitRoom 退房', '被服务器踢出当前房间', '当前房间整个被解散'];
					// uni.showToast({
					// 	title: `退房 ${reasonList[reason]}`,
					// 	icon: 'none',
					// 	duration: 1000
					// });
				});
				this.trtcCloud.on('onFirstVideoFrame', (res) => {
					console.log(`渲染的首帧画面响应 = ${JSON.stringify(res)}`);
				});
				this.trtcCloud.on('onRemoteUserEnterRoom', (userId) => {
					this.remoteUserId = userId;
					// uni.showToast({
					// 	title: `远端进房: userId = ${userId}`,
					// 	icon: 'none',
					// });
				});
				this.trtcCloud.on('onUserVideoAvailable', (res) => {
					const {
						userId,
						available
					} = res;
					console.log('onUserVideoAvailable = ', res);
					if (userId && available) {
						this.remoteUserId = userId;
					}else{
						this.remoteUserId = '';
					}
				});
				this.trtcCloud.on('onSnapshotComplete', (res) => {
					const {
						base64Data,
						message
					} = res;
					console.log("截图回调base64Data", res)
					// console.log("截图回调stringify",JSON.stringify(res.base64Data))
					// this.imgs = /data:image\/(\w+);base64,(.*)/.exec(base64Data)

					this.saveImage(base64Data);
				});
			},
			// 将base64字符串转换为NSData
			base64ToData(base64String) {
				var decodedData = NSData.alloc().initWithBase64EncodedStringOptions(base64String, 1);
				return decodedData;
			},

			// 将NSData转换为UIImage对象
			dataToImage(data) {
				var image = UIImage.imageWithData(data);
				return image;
			},

			// 将UIImage对象转换为PNG格式的NSData数据
			imageToPNGData(image) {
				var pngData = UIImagePNGRepresentation(image);
				return pngData;
			},

			// 将NSData对象写入文件
			writeDataToFile(data, filePath) {
				var success = data.writeToFileAtomically(filePath, true);
				if (success) {
					console.log("写入文件成功");
				} else {
					console.log("写入文件失败");
				}
			},



			// /api/Trtc/start
			async trtcStart() {
				await uni.request({
					url: '/Trtc/start',
					method: 'post',
					data: {
						room_id: this.roomId,
						user_id: this.userId
					},
					success: res => {
						console.log('房间开播', res)
					}
				});
			},
			handleUninstallEvents() {
				this.trtcCloud.off('*');
			}
		}
	}
</script>

<style>
	.conter {
		flex: 1;
		
	}

	.plug {
		width: 750rpx;
		flex: 1;
	}

	.trtcView {
		width: 750rpx;
		height: calc(100vh - 44px);
		flex: 1;
		z-index: 999;
		position: absolute;
		top: 0;
		left: 0;
	}

	.footer {
		width: 100%;
		height: 50px;
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 999;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.hangUp {
		width: 50px;
		height: 50px;
		position: fixed;
		left: 325rpx;
		bottom: 50px;
	}

	.hangUpImg {
		width: 100%;
		height: 100%;
	}

	.overturn {
		width: 52rpx;
		height: 52rpx;
		font-size: 24px;
		position: fixed;
		bottom: 100rpx;
		right: 30rpx;
	}

	.overturnImg {
		width: 100%;
		height: 100%;
		background: #eee;
	}

	.bg {
		width: 750rpx;
		flex: 1;
		background: #e5f8fe;
		position: absolute;
		z-index: 99;
		top: 0;
		left: 0;
	}

	.box {
		padding: 30rpx;
	}

	.boxConter {
		/* width: 100%; */
		height: auto;
		padding: 30rpx;
		background: #fff;
		border-radius: 20rpx;
	}

	.boxConterTime {
		width: 200rpx;
		height: 200rpx;
		border-radius: 100%;
		margin: 0 auto;
	}

	.u-progress-info {
		font-size: 30rpx;
		font-weight: bold;
	}

	.boxConterTitle {
		font-size: 36rpx;
		font-weight: bold;
		margin-top: 40rpx;

	}

	.boxConterFlex {
		width: 100%;
		height: auto;
		display: flex;
		flex-wrap: wrap;
	}

	.boxConterImg {
		width: 190rpx;
		height: 190rpx;
		margin-top: 20rpx;
		margin-left: 20rpx;
	}

	.boxConterImg:nth-child(1) {
		/* margin-left: 0; */
	}

	.boxConterImg:nth-child(4) {
		/* margin-left: 0; */
	}

	.boxConterBtn {
		width: 100%;
		height: 80rpx;
		border-radius: 40rpx;
		background: linear-gradient(to right, #13b1b4, #22e59f);
		text-align: center;
		line-height: 80rpx;
		font-size: 32rpx;
		color: #fff;
		font-weight: bold;
		margin: 40rpx auto 0 auto;
	}
</style>